<template>
    <div class="segment-details-container">
        <el-card class="page-card">
            <template #header>
                <div class="card-header">
                    <span class="card-title">分档明细</span>
                    <div class="header-actions">
                        <el-select v-model="selectedWorkshop" placeholder="选择车间"
                            style="width: 200px; margin-right: 10px;" @change="filterByWorkshop">
                            <el-option value="" label="全部车间"></el-option>
                            <el-option v-for="workshop in workshopList" :key="workshop" :value="workshop"
                                :label="workshop"></el-option>
                        </el-select>
                        <el-button type="primary" :icon="Download" @click="saveAsImage" :loading="saving">
                            保存为图片
                        </el-button>
                    </div>
                </div>
            </template>

            <div v-loading="loading" class="content-wrapper">
                <!-- 数据更新时间信息 -->
                <div v-if="lastUpdateInfo" class="update-info">
                    <el-alert :title="`${lastUpdateInfo.workshop} 车间数据最后更新时间: ${lastUpdateInfo.time}`" type="info"
                        :closable="false" style="margin-bottom: 20px;" />
                </div>

                <!-- 分档明细表格 -->
                <div ref="tableContainer" id="segment-table-container">
                    <div v-for="workshopData in displayData" :key="workshopData.workshop" class="workshop-section">
                        <h3 class="workshop-title">{{ workshopData.workshop }} 车间</h3>

                        <el-table :data="workshopData.segments" border style="width: 100%; margin-bottom: 30px;"
                            :row-style="getRowStyle">
                            <el-table-column type="index" label="序号" width="80" align="center" />
                            <el-table-column prop="line" label="线别" width="150" align="center" />
                            <el-table-column prop="current_segment" label="在用分档" width="800" align="center">
                                <template #default="scope">
                                    <span class="segment-highlight" :style="{
                                        backgroundColor: getSegmentColor(scope.row.current_segment),
                                        color: '#333333'
                                    }">
                                        {{ scope.row.current_segment }}
                                    </span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="ip" label="IP地址" width="150" align="center" />
                            <el-table-column label="启用状态" width="100" align="center">
                                <template #default="scope">
                                    <el-tag :type="scope.row.is_enabled ? 'success' : 'danger'" size="small">
                                        {{ scope.row.is_enabled ? '已启用' : '未启用' }}
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column prop="updated_at" label="更新时间" align="center" />
                        </el-table>
                    </div>
                </div>

                <!-- 空数据提示 -->
                <el-empty v-if="!loading && displayData.length === 0" description="暂无分档明细数据" />
            </div>
        </el-card>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Download } from '@element-plus/icons-vue'
import axios from 'axios'
import html2canvas from 'html2canvas'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const segmentData = ref([])
const selectedWorkshop = ref('')
const segmentColorMap = ref({})

// 计算属性
const workshopList = computed(() => {
    return [...new Set(segmentData.value.map(item => item.workshop))]
})

const displayData = computed(() => {
    if (!selectedWorkshop.value) {
        return segmentData.value
    }
    return segmentData.value.filter(item => item.workshop === selectedWorkshop.value)
})

const lastUpdateInfo = computed(() => {
    if (!displayData.value.length) return null

    if (selectedWorkshop.value) {
        const workshopData = displayData.value[0]
        return {
            workshop: workshopData.workshop,
            time: workshopData.last_updated
        }
    } else {
        // 显示最近更新的车间信息
        let latestWorkshop = displayData.value[0]
        for (const workshop of displayData.value) {
            if (new Date(workshop.last_updated) > new Date(latestWorkshop.last_updated)) {
                latestWorkshop = workshop
            }
        }
        return {
            workshop: latestWorkshop.workshop,
            time: latestWorkshop.last_updated
        }
    }
})

// 颜色生成函数
const generateColors = (segments) => {
    const colors = [
        '#E8F5E8', '#E3F2FD', '#FFF3E0', '#F3E5F5', '#FCE4EC',
        '#E0F2F1', '#F1F8E9', '#FFF8E1', '#EDE7F6', '#E8EAF6',
        '#F9FBE7', '#FFE0B2', '#FFCDD2', '#D1C4E9', '#C8E6C9',
        '#BBDEFB', '#FFE0B2', '#F8BBD9', '#B2DFDB', '#DCEDC8'
    ]

    const uniqueSegments = [...new Set(segments)]
    const colorMap = {}

    uniqueSegments.forEach((segment, index) => {
        colorMap[segment] = colors[index % colors.length]
    })

    return colorMap
}

// 获取分档颜色
const getSegmentColor = (segment) => {
    return segmentColorMap.value[segment] || '#666666'
}

// 获取行样式
const getRowStyle = ({ row }) => {
    const backgroundColor = segmentColorMap.value[row.current_segment] || '#ffffff'
    return {
        backgroundColor: backgroundColor,
        transition: 'background-color 0.3s ease'
    }
}

// 根据车间筛选
const filterByWorkshop = () => {
    // 重新计算颜色映射（只针对当前显示的数据）
    const currentSegments = displayData.value.flatMap(workshop =>
        workshop.segments.map(seg => seg.current_segment)
    )
    segmentColorMap.value = generateColors(currentSegments)
}

// 获取分档明细数据
const fetchSegmentDetails = async () => {
    loading.value = true
    try {
        const response = await axios.get('/api/segment-details/')
        if (response.data.success) {
            segmentData.value = response.data.data

            // 生成颜色映射
            const allSegments = segmentData.value.flatMap(workshop =>
                workshop.segments.map(seg => seg.current_segment)
            )
            segmentColorMap.value = generateColors(allSegments)

            ElMessage.success('分档明细数据加载成功')
        } else {
            ElMessage.error(response.data.message || '获取分档明细失败')
        }
    } catch (error) {
        console.error('获取分档明细出错:', error)
        ElMessage.error('获取分档明细失败')
    } finally {
        loading.value = false
    }
}

// 保存为图片
const saveAsImage = async () => {
    saving.value = true
    try {
        const element = document.getElementById('segment-table-container')
        if (!element) {
            ElMessage.error('未找到要保存的内容')
            return
        }

        const canvas = await html2canvas(element, {
            backgroundColor: '#ffffff',
            scale: 2, // 提高图片质量
            useCORS: true,
            allowTaint: true
        })

        // 创建下载链接
        const link = document.createElement('a')
        link.download = `分档明细_${selectedWorkshop.value || '全部车间'}_${new Date().toISOString().slice(0, 19).replace(/[:-]/g, '')}.png`
        link.href = canvas.toDataURL('image/png')
        link.click()

        ElMessage.success('图片保存成功')
    } catch (error) {
        console.error('保存图片出错:', error)
        ElMessage.error('保存图片失败')
    } finally {
        saving.value = false
    }
}

// 组件挂载
onMounted(() => {
    fetchSegmentDetails()
})
</script>

<style scoped>
.segment-details-container {
    padding: 20px;
}

.page-card {
    min-height: calc(100vh - 120px);
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-title {
    font-size: 18px;
    font-weight: bold;
    color: #303133;
}

.header-actions {
    display: flex;
    align-items: center;
}

.content-wrapper {
    min-height: 400px;
}

.update-info {
    margin-bottom: 20px;
}

.workshop-section {
    margin-bottom: 30px;
}

.workshop-title {
    font-size: 18px;
    font-weight: bold;
    color: #409EFF;
    margin-bottom: 15px;
    padding-bottom: 8px;
    border-bottom: 2px solid #409EFF;
}

:deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;
    font-size: 15px;
}

:deep(.el-table th) {
    background-color: #f5f7fa;
    color: #606266;
    font-weight: bold;
    font-size: 15px;
}

:deep(.el-table td) {
    padding: 15px 0;
    border-bottom: 1px solid #e4e7ed;
    font-size: 15px;
}

:deep(.el-table tbody tr:hover > td) {
    background-color: rgba(64, 158, 255, 0.1) !important;
}

:deep(.el-table .el-table__row) {
    transition: background-color 0.3s ease;
}

/* 提高分档显示的可读性 */
.segment-highlight {
    font-weight: bold;
    font-size: 15px;
    padding: 6px 10px;
    border-radius: 4px;
    display: inline-block;
    border: 1px solid rgba(0, 0, 0, 0.1);
}

:deep(.el-alert) {
    border-radius: 8px;
}

/* 打印样式 */
@media print {
    .header-actions {
        display: none;
    }

    .update-info {
        margin-bottom: 10px;
    }

    .workshop-section {
        page-break-inside: avoid;
        margin-bottom: 20px;
    }
}
</style>
